package com.zzy.bridge;

import com.alibaba.fastjson.JSONObject;
import com.zzy.RegisterLoginType;
import com.zzy.pojo.UserInfo;
import com.zzy.repo.UserRepository;
import com.zzy.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: zzy
 * @CreateTime: 2024-09-30
 * @Description: 默认实现
 * @Version: 1.0
 */
@Component
@RegisterLoginType(RegisterLoginEnum.GITEE)
public class RegisterLoginByGitee extends AbstractRegisterLoginFunc implements RegisterLoginFuncInterface {

    @Value(value = "${gitee.state}")
    private String giteeState;

    @Value(value = "${gitee.token.url}")
    private String giteeTokenUrl;

    @Value(value = "${gitee.user.url}")
    private String giteeUserUrl;

    @Value(value = "${gitee.user.prefix}")
    private String giteeUserPrefix;

    @Autowired
    private UserRepository userRepository;

    @Override
    public String login(String account, String password) {
        return super.commonLogin(account, password, userRepository);
    }

    @Override
    public String register(UserInfo userInfo) {
        return super.commonRegister(userInfo, userRepository);
    }

    @Override
    public boolean checkUserExist(String userName) {
        return super.commonCheckUserExist(userName, userRepository);
    }

    @Override
    public String login3rd(HttpServletRequest request) {
        String state = request.getParameter("state");
        String code = request.getParameter("code");
        if(!giteeState.equals(state)) {
            throw new UnsupportedOperationException("Invalid State!");
        }
        String tokenUrl = giteeTokenUrl.concat(code);
        JSONObject tokenResponse = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        String token = tokenResponse.getString("access_token");
        String userUrl = giteeUserUrl.concat(token);
        String name = HttpClientUtils.execute(userUrl, HttpMethod.GET).getString("name");
        String userName = giteeUserPrefix.concat(name);
        String password = userName;
        return autoRegister3rdAndLogin(userName, password);
    }

    private String autoRegister3rdAndLogin(String userName, String password) {
        // 如果三方已经登陆过，直接登录
        if(checkUserExist(userName)){
            return login(userName, password);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setCreateDate(new Date());
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        register(userInfo);
        return login(userName, password);
    }
}
